package com.ironman.sailboat.mobile;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ironman.sailboat.mobile.context.MockConfigContext;
import com.ironman.sailboat.mobile.properties.SysTrainingProperties;
import com.ironman.sailboat.mobile.threadpool.ThreadPool;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.codec.MqttQoS;
import org.dromara.mica.mqtt.spring.client.MqttClientTemplate;
import org.noear.snack.ONode;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Getter
@Setter
public abstract class AbstractMqttClient {

    @Resource
    SysTrainingProperties sysTrainingProperties;

    @Resource
    MqttClientTemplate mqttClientTemplate;

    public void publish(String topicTemplate, ONode data) {
        String topic = StrUtil.format(topicTemplate, MockConfigContext.toTenantCode(), MockConfigContext.toLevelId(), MockConfigContext.toMHmId());
        data.set("ts", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        data.set("mHmId", MockConfigContext.toMHmId());
        ThreadPool.FIXED_EXECUTOR.submit(() -> {
            log.info("{}: {}", topic, data.toJson());
            mqttClientTemplate.publish(topic, JSONUtil.parseObj(data.toJson()), MqttQoS.QOS1);
        });
    }
}
